import { Button, Table, Form, Input, message, Popconfirm, Select } from 'antd'
import ModalBox from '../../../components/modalBox'
import { useState, useEffect  } from 'react';
import { service } from '../../../api/url.js'
import dayjs from 'dayjs'
import store from '../../../store/store.js'
const sha1 = require('sha1');
const _state = store.getState()
const { TextArea } = Input;
function MyApp(props) {
    const columns = [
        {
            title: '序号',
            width: '5%',
            align: 'center',
            render: (text, record, index) => {
                return index + 1
            }
        },
        {
            title: '用户名',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center'
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
            align: 'center',
        },
        {
            title: '身份',
            dataIndex: 'type',
            key: 'type',
            align: 'center',
            render: (text, record, index) => {
                switch(record.type) {
                    case '0':
                        return (<>普通用户</>);
                    case '1':
                        return (<>管理员</>);
                }
            }
        },
        {
            title: 'token',
            dataIndex: 'token',
            key: 'token',
            align: 'center',
            width: '15%',
        },
        {
            title: '创建日期',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
            width: '15%',
            render: (text, record, index) => {
                return(<>{record['createTime'] ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : ''}</>)
            }
        },
        {
            title: '操作',
            width: '15%',
            align: 'center',
            render: (text, record, index) => {
                return (
                    <div>
                        <Button type="primary" style={{marginRight: '10px'}} onClick={() => {editUser(record)}}>修改</Button>
                        <Popconfirm
                            title="删除用户"
                            description="是否确定删除该用户?"
                            onConfirm={() => confirm(record)}
                            okText="是"
                            cancelText="否"
                          >
                            <Button type="primary" danger>
                                删除
                            </Button>
                          </Popconfirm>
                    </div>
                )
            }
        }
    ]
    const [dataSource, setDataSource] = useState([])
    const [total, setTotal] = useState(0)
    const [messageApi, contextHolder] = message.useMessage();
    const [showModal, setShowModal] = useState(false)
    const [UserInfo, setUserInfo] = useState({
        phone: '',
        formModel: ''
    })
    const success = (msg) => {
        messageApi.open({
            type: 'success',
            content: msg,
        });
    };
    const error = (msg) => {
        messageApi.open({
            type: 'error',
            content: msg,
        });
    };
    const confirm = (row) => {
      setUserInfo({formModel: '', phone: row.phone})
      delUser(row)
    };
    const [form] = Form.useForm();
    const onSave = () => {
        form.validateFields()
             .then((res) => {
                console.log('验证成功');
                const fromData = form.getFieldsValue()
                const params = {
                    phone: fromData.phone,
                    userName: fromData.userName,
                    type: fromData.type,
                    token: fromData.token,
                    password: sha1(fromData.password)
                }
                addUser(params)
              })
              .catch((err) => {
                console.log('验证失败');
              })
        
    }
    const onCancle = () => {
        setShowModal(false)
    }
    // 编辑用户
    const editUser = (row) => {
        console.log('row', row)
        setUserInfo({formModel: 'edit', phone: row.phone})
        setShowModal(true)
        setTimeout(() => {
            form.setFieldsValue({
                phone: row.phone,
                userName: row.userName,
                type: row.type,
                token: row.token
            })
        }, 200)
    }
    // 添加/修改项目信息
    const addUser = (params) => {
        UserInfo.formModel === 'add' ?
        service.addUser(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getUserList()
                onCancle()
            } else {
                error(res.data.msg)
            }
        }) :
        service.putUser(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getUserList()
                onCancle()
            } else {
                error(res.data.msg)
            }
        })
    }
    // 获取用户列表
    const getUserList = () => {
        const params = {
            pageNum: 1,
            pageSize: 10
        }
        service.allUser(params).then(res => {
            if (res.data.status === 1) {
                setDataSource(res.data.data.list)
                setTotal(res.data.data.total)
                success(res.data.msg)
            } else {
                error(res.data.msg)
            }
        })
    }
    // 删除用户
    const delUser = (row) => {
        const params = {
            phone: row.phone
        }
        service.delUser(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getUserList()
            } else {
                error(res.data.msg)
            }
        })
    }
    useEffect(() => {
        getUserList()
    }, [])
    useEffect(() => {
        if (showModal) {
            form.resetFields()
        }
    }, [showModal, UserInfo]);
    const modalCompoennt = <ModalBox title={UserInfo.formModel === 'add' ? '添加用户' : '编辑用户'} showModal={showModal}>
        <Button type="dashed" onClick={() => {setShowModal(true);setUserInfo({formModel: 'add', phone: ''})}}>新增</Button>
        <div className="modal-box-body">
            <Form
                form={form}
                className="app-form"
                name="basic"
                labelCol={{
                  span: 4,
                }}
                wrapperCol={{
                  span: 20,
                }}
                style={{
                  maxWidth: 600,
                }}
                initialValues={{
                  remember: true,
                }}
                autoComplete="off"
              >
                <Form.Item
                  label="手机号："
                  name="phone"
                >
                  <Input disabled={UserInfo.formModel === 'edit'} placeholder="请输入手机号"/>
                </Form.Item>
                
                <Form.Item
                  label="用户名："
                  name="userName"
                  rules={[
                    {
                      required: true,
                      message: '用户名不能为空!',
                    }
                  ]}
                >
                  <Input placeholder="请输入用户名"/>
                </Form.Item>
                {UserInfo.formModel === 'add' ? <Form.Item
                  label="密码："
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: '密码不能为空!',
                    }
                  ]}
                >
                  <Input.Password placeholder="请输入密码"/>
                </Form.Item> : <></>}
                <Form.Item
                  label="角色："
                  name="type"
                  rules={[
                    {
                      required: true,
                      message: '角色不能为空!',
                    }
                  ]}
                >
                  <Select
                        placeholder="请选择角色"
                        defaultValue="0"
                        options={[
                          {
                            label: '普通用户',
                            value: '0',
                          },
                          {
                            label: '管理员',
                            value: '1',
                          }
                        ]}
                      />
                </Form.Item>
                <Form.Item
                  label="token："
                  name="token"
                >
                  <Input disabled={true} placeholder="请获取token"/>
                </Form.Item>
              </Form>
        </div>
        <div className="ctrl-btn-bar btn-bar-right">
              <Button className="login-btn" type="primary" onClick={onSave}>
                保存
              </Button>
              <Button onClick={onCancle}>
                取消
              </Button>
        </div>
    </ModalBox>
    return (
        <div className="my-app">
            {contextHolder}
            <div className="table-header">
                <h3>用户列表</h3> 
                {modalCompoennt}
            </div>
            <div className="table-container">
                <Table bordered dataSource={dataSource} columns={columns} rowKey="phone" scroll={{y: 710}}/>
            </div>
            
        </div>
    )
}
export default MyApp